package com.librariy.util;
import android.app.Activity;
import android.app.Dialog;
import android.util.SparseArray;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.librariy.view.SpanTextView;
public class ViewBinder {
    private final Object mHolder;
    private SparseArray<Object> mViewMap = new SparseArray<Object>();
    public ViewBinder(Dialog mDialog) {
        this.mHolder = mDialog;
    }
    public ViewBinder(View mContentView) {
        this.mHolder = mContentView;
    }
    public ViewBinder(Activity mActivity) {
        this.mHolder=mActivity;
    }
    @SuppressWarnings("unchecked")
    public <T extends View> T getRootView() {
        if(mHolder instanceof Activity){
            return (T)(((Activity)mHolder).getWindow().getDecorView());
        }else if(mHolder instanceof Dialog){
            return (T)((Dialog)mHolder).getWindow().getDecorView();
        }else if(mHolder instanceof View){
            return (T)((View)mHolder);
        }else{
            return null;
        }
    }
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId) {
        Object tagetView = mViewMap.get(viewId);
        if (tagetView == null) {
            tagetView = this.getRootView().findViewById(viewId);
            mViewMap.put(viewId, tagetView);
        }
        return tagetView == null ? null : (T) tagetView;
    }
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId,Class<T> mClass) {
        Object tagetView = mViewMap.get(viewId);
        if (tagetView == null) {
            tagetView = this.getRootView().findViewById(viewId);
            mViewMap.put(viewId, tagetView);
        }
        return tagetView == null ? null : (T) tagetView;
    }
    public TextView getTextView(int viewId) {
        return getView(viewId,TextView.class);
    }

    public EditText getEditText(int viewId) {
        return getView(viewId, EditText.class);
    }

    public int getColor(int colorResid) {
        Object tagetColor = mViewMap.get(colorResid);
        if (tagetColor==null) {
            tagetColor=this.getRootView().getResources().getColor(colorResid);
            mViewMap.put(colorResid, tagetColor);
        }
        return tagetColor == null ? 0 : (Integer) tagetColor;
    }
    @Deprecated
    public void setText(int viewId, CharSequence text) {
        View tagetView = getView(viewId);
        if (tagetView instanceof TextView) {
            ((TextView) tagetView).setText(text);
        }
    }
    @Deprecated
    public void setSpanText(int viewId, String[] optSplitArray) {
        SpanTextView tagetView = getView(viewId);
        tagetView.setSpanText(optSplitArray);
    }

    public void displayImage(int viewId, String mUrl, int defaultImg) {
        ImageView tagetView = getView(viewId);
        ImageLoader.displayImage(mUrl, tagetView, defaultImg);
    }
}